from urllib import error

from flask import Flask, Blueprint, render_template, session, redirect, url_for, request, Response, jsonify
# 这里注意要导入models中的models，而不是extends中的models
from App.models import *
import urllib
import urllib.request as request
import urllib.error as error
import json

weatherblue = Blueprint('watherblue', __name__)


@weatherblue.route('/weather', methods=['GET', 'POST'])
def weather():
    api_url = 'http://apis.juhe.cn/simpleWeather/query'
    params_dict = {
        "city": "长沙",  # 查询天气的城市名称，如：北京、苏州、上海
        "key": "b09bcbed6f7e6cc442809b78dace8b82",  # 您申请的接口API接口请求Key
    }
    params = urllib.parse.urlencode(params_dict)
    try:
        req = request.Request(api_url, params.encode())
        response = request.urlopen(req)
        content = response.read()
        if content:
            try:
                result = json.loads(content)
                error_code = result['error_code']
                output = []
                if (error_code == 0):
                    temperature = result['result']['realtime']['temperature']
                    humidity = result['result']['realtime']['humidity']
                    info = result['result']['realtime']['info']
                    wid = result['result']['realtime']['wid']
                    direct = result['result']['realtime']['direct']
                    power = result['result']['realtime']['power']
                    aqi = result['result']['realtime']['aqi']
                    output.append({
                        '城市': '长沙',
                        '温度': temperature,
                        '湿度': humidity,
                        '天气': info,
                        '天气标识': wid,
                        '风向': direct,
                        '风力': power,
                        '空气质量': aqi
                    })
                    return jsonify(output)
                    # print("温度：%s\n湿度：%s\n天气：%s\n天气标识：%s\n风向：%s\n风力：%s\n空气质量：%s" % (
                    #     temperature, humidity, info, wid, direct, power, aqi))
                else:
                    output = '错误码:' + result['error_code'] + '\r\n'
                    output += '原因:' + result['reason']
                    return output
            except Exception as e:
                print(e)
                return '请求异常1'
        else:
            # 可能网络异常等问题，无法获取返回内容，请求异常
            return '请求异常2'
    except error.HTTPError as err:
        print(err)
    except error.URLError as err:
        # 其他异常
        print(err)


@weatherblue.route('/futureWeather', methods=['GET', 'POST'])
def futureWeather():
    api_url = 'http://apis.juhe.cn/simpleWeather/query'
    params_dict = {
        "city": "长沙",  # 查询天气的城市名称，如：北京、苏州、上海
        "key": "b09bcbed6f7e6cc442809b78dace8b82",  # 您申请的接口API接口请求Key
    }
    params = urllib.parse.urlencode(params_dict)
    try:
        req = request.Request(api_url, params.encode())
        response = request.urlopen(req)
        content = response.read()
        if content:
            try:
                result = json.loads(content)
                error_code = result['error_code']
                output = []
                if (error_code == 0):
                    for i in result['result']['future']:
                        print(i)
                        date = i['date']
                        temperature = i['temperature']
                        weather = i['weather']
                        direct = i['direct']
                        output.append({
                            '日期': date,
                            '温度': temperature,
                            '天气': weather,
                            '风向': direct
                        })
                    return jsonify(output)
                    # print("温度：%s\n湿度：%s\n天气：%s\n天气标识：%s\n风向：%s\n风力：%s\n空气质量：%s" % (
                    #     temperature, humidity, info, wid, direct, power, aqi))
                else:
                    output = '错误码:' + result['error_code'] + '\r\n'
                    output += '原因:' + result['reason']
                    return output
            except Exception as e:
                print(e)
                return '请求异常1'
        else:
            # 可能网络异常等问题，无法获取返回内容，请求异常
            return '请求异常2'
    except error.HTTPError as err:
        print(err)
    except error.URLError as err:
        # 其他异常
        print(err)
